//
//  MyCenterViewController.m
//  HMShoperApp
//
//  Created by chirui on 2018/6/20.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "MyCenterViewController.h"
#import "ChangePwViewController.h"
#import "FeedBackViewController.h"
#import "JPUSHService.h"
#import "LogingViewController.h"
#import "TotailsViewController.h"


@interface MyCenterViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    
    UITableView * _tableView;
    NSDictionary * userDic;
    UIButton * userIconBtn;
}

@end

@implementation MyCenterViewController
-(void)viewWillDisappear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden =NO;
    
}

-(void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = YES; //隐藏
    self.tabBarController.tabBar.hidden = NO;
   
    if (verifTokenAndEnter) {
  
//        [self getUserMessageRequest];
//        [self getMessageCountRequest];
//        [self getOrderCountRequest];
    }else {
        
        userDic = nil;
        
    }
}

#pragma mark - UINavigationControllerDelegate
// 将要显示控制器
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    [self creatTableView];
}


-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, -SH_StatusBarHeight, WIDTH, HEIGHT-SH_StatusBarHeight+SH_TabBarHeight) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
     [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    //    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //
    //
    //
    //    }];
    //    _tableView.mj_header = header;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 3;
    }else {
        return 2;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 55;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
         return 120+SH_TopHeight;
    }else{
        
         return 10;
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellId = @"cellId";
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:cellId ];
    if (cell==nil) {
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    NSArray * array =@[@"单量统计",@"修改密码",@"意见反馈"];
   NSArray * array_two = @[@"清除缓存",@"退出登录"];
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(10, 54.5, WIDTH -20,0.5)];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:view];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    if (indexPath.section==0) {
        cell.textLabel.text = array[indexPath.row];
    }else{
        
        cell.textLabel.text = array_two[indexPath.row];
    }
    if (indexPath.section==1) {
        if (indexPath.row==0) {
            double tmpSize = [[SDImageCache sharedImageCache]getSize]/1024/1024;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2fM",tmpSize];
            
        }
    }
    
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section==0) {
        
    UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120+SH_TopHeight)];
    heardView.backgroundColor = [UIColor whiteColor];
    
    UIImageView * bgImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120+SH_TopHeight)];
    bgImage.userInteractionEnabled = YES;
    bgImage.image = ImageName(@"img_bg");
    [heardView addSubview:bgImage];
    
    userIconBtn = [self btnFrame:CGRectMake(10, (100+SH_TopHeight)/2-10, 60, 60) andImageName:@"img_head_portrait_pre" andSEL:@selector(photoClick) onView:bgImage];
        
        [userIconBtn sd_setImageWithURL:ImageUrl(USER_DEFAULTGet(@"avatar")) forState:UIControlStateNormal placeholderImage:ImageName(@"img_head_portrait_pre")];
    userIconBtn.layer.cornerRadius = 30.f;
    userIconBtn.layer.masksToBounds = YES;
    
    UILabel * userNameLabel =[[UILabel alloc]initWithFrame:CGRectMake(80, (100+SH_TopHeight)/2+10, 200, 22)];
    userNameLabel.font =[UIFont systemFontOfSize:16];
    userNameLabel.textColor =[UIColor whiteColor];
    userNameLabel.text = USER_DEFAULTGet(@"user_name");
    userNameLabel.numberOfLines = 1;
    [userNameLabel sizeToFit];
    [bgImage addSubview:userNameLabel];
    
    UILabel * titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(100, 30, WIDTH -200, 20)];
    titleLabel.font =[UIFont boldSystemFontOfSize:17];
    titleLabel.textColor =[UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"个人中心";
    [bgImage addSubview:titleLabel];
    
    
    if (userDic) {
        [userIconBtn sd_setBackgroundImageWithURL:ImageUrl(userDic[@"avatar"]) forState:UIControlStateNormal placeholderImage:ImageName(@"img_head_portrait_pre")] ;
        userNameLabel.text = userDic[@"user_name"];
        userNameLabel.numberOfLines = 1;
        [userNameLabel sizeToFit];
    }
    
   
    
    return heardView;
    }else {
        
        return nil;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==0) {
        if(indexPath.row==0){
            TotailsViewController* totails = [[TotailsViewController alloc]init];
            totails.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:totails animated:YES];
            
        }else  if (indexPath.row==1) {
            ChangePwViewController * change = [[ChangePwViewController alloc]init];
            change.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:change animated:YES];
        }else if(indexPath.row==2){
            FeedBackViewController* feed = [[FeedBackViewController alloc]init];
            feed.hidesBottomBarWhenPushed = YES;
            self.navigationController.navigationBar.translucent = NO;
            [self.navigationController pushViewController:feed animated:YES];
        }
    }else {
        
        if (indexPath.row==0) {
            //清除缓存
            double tmpSize = [[SDImageCache sharedImageCache]getSize]/1024/1024;
            
            UIAlertView * alert =[[UIAlertView alloc]initWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"当前缓存%.2fM",tmpSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 1000;
            [alert show];
        }else{
            UIAlertView * alert =[[UIAlertView alloc]initWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"退出登录？"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 1001;
            [alert show];
           
        }
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 1000) {
        
        if (buttonIndex==0) {
            NSLog(@"cannel");
        }else {
            
            [[SDImageCache sharedImageCache]clearDisk];
            [_tableView reloadData];
        }
    }
    if (alertView.tag == 1001) {
        
        if (buttonIndex==0) {
            NSLog(@"cannel");
        }else {
            [self setLogingOut];
            
        }
    }
    
}

-(void)photoClick{
    
//    change_photo_api
    
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            
            [self upIconImageRequestFor:image];
        }
    }];
    
}

-(UIButton *)btnFrame:(CGRect)rec andImageName:(NSString *)imageName andSEL:(SEL)sel onView:(UIView *)view{
    
    UIButton * scanBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    scanBtn.frame = rec;
    [scanBtn setBackgroundImage:ImageName(imageName) forState:UIControlStateNormal];
    [scanBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scanBtn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    scanBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [view addSubview:scanBtn];
    return scanBtn;
    
}

// 有头像跟名称的
-(void)upIconImageRequestFor:(UIImage *)image {
    
    NSDictionary * dic = @{@"user_id":USER_DEFAULTGet(@"user_id"),
                           @"token":USER_DEFAULTGet(@"token"),
                           };
   NSData *  data = UIImageJPEGRepresentation(image, 0.4);
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:RequestUrlStr(change_photo_api) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"avatar" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
              USER_DEFAULTSet(responseObject[@"datas"][@"avatar"], @"avatar");
            
            [userIconBtn sd_setBackgroundImageWithURL:ImageUrl(responseObject[@"datas"][@"avatar"]) forState:UIControlStateNormal];
        }else{
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        [_tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    } ];
    
}

-(void)setLogingOut{
    
   

        
        [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {

            NSLog(@"rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);

        } seq:0];
        SHuiMBhudTextTimeStr(@"退出成功，请重新登录！");
        
        USER_DEFAULTSet(@"", @"token");
        USER_DEFAULTSet(@"", @"enter");
        USER_DEFAULTSet(@"", @"tokenVerify");
        USER_DEFAULTSet(@"", @"mid");
        USER_DEFAULTSet(@"", @"phone");
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1.5* NSEC_PER_SEC)), dispatch_get_main_queue(),^{
            
            LogingViewController * tabbar  =[[LogingViewController alloc]init];
            
            [UIApplication sharedApplication].keyWindow.rootViewController =tabbar;
            
        });

}


@end
